<?php

namespace App\Console\Commands;

use App\Model\Temp;
use Goutte\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class StockCrawler extends Command
{
    public $tempModel;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'crawler:stock';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时抓取股票数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Temp $tempModel)
    {
        $this->tempModel = $tempModel;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $res = $this->getContents('https://query1.finance.yahoo.com/v8/finance/chart/AIXN?range=1d&includePrePost=false&interval=2m&corsDomain=hk.finance.yahoo.com&.tsrc=finance');
        $data = json_decode($res);
        $stock = $data->chart->result[0]->meta->previousClose;
        $this->info($stock);
        if (!empty($stock)){
            $this->tempModel->updateStock($stock);
            $this->info('抓取成功');
            return true;
        }
    }

    public function getContents($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
